﻿using ConsoleApplication.WebAPI;
using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Orm.DataEntity;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HM
{
    [Description("聚合账核销结果，合同（退货单）自动下推销售直接调拨单")]
    public class HTPushDB : IScheduleService
    {
        public void Run(Context ctx, Schedule schedule)
        {
            try
            {
                var result = InvokeHelper.Login();
                var iResult = JObject.Parse(result)["LoginResultType"].Value<int>();
                if (iResult == 1)
                {
                    string FBILLNO = "", FEntryId = "", htFENTRYID="";
                    string SQL = "/*dialect*/" + string.Format(@"SELECT F_RXWU_Text6,FMATERIALID into #F FROM RXWU_t_Cust_Entry100013 where F_RXWU_Text2='销售出仓' and F_RXWU_TEXT15=''
select T.F_RXWU_TEXT,t3.FNUMBER,T1.FENTRYID,T.FBILLNO,T.FDATE into #C from T_CRM_CONTRACT t
					left join T_CRM_CONTRACTENTRY t1 on t.FID=t1.FID
					left join T_CRM_CONTRACTENTRY_R t2 on t1.FENTRYID=t2.FENTRYID
					LEFT join T_BD_MATERIAL t3 on t1.FMATERIALID=t3.FMATERIALID
					where t1.F_RXWU_QTY=0 and t2.FSALEQTY=0

					SELECT row_number() over(partition by t3.FENTRYID order by t3.FENTRYID  ) as FSEQ, t3.FENTRYID htFENTRYID,T1.FEntryID,t3.FBILLNO into #D from RXWU_t_Cust100002 t
					left join
					RXWU_t_Cust_Entry100013 t1 on  t.fid=t1.fid
					LEFT JOIN T_BD_MATERIAL T2 ON T1.FMATERIALID=T2.FMATERIALID
					right JOIN #C T3 ON T1.F_RXWU_Text6=T3.F_RXWU_TEXT AND T2.FNUMBER=T3.FNUMBER
					WHERE (T1.F_RXWU_Text2='销售出仓'
					and (T1.F_RXWU_TEXT15<>'AutoCheck'and T1.F_RXWU_TEXT15<>'UserCheck')
                    AND (t1.F_RXWU_Text16<>'补发订单'
                    AND t1.F_RXWU_Text16<>'换货订单')
                    and(T1.F_RXWU_DATE2>t3.FDATE))
                    AND  t3.FDATE>(select max(fclosedate)fclosedate from t_stk_closeprofile where fcategory = 'STK' and FORGID=100071 group by forgid)
					OR (T1.F_RXWU_TEXT15='' and T1.F_RXWU_Text2='销售出仓' and t1.F_RXWU_Text16<>'补发订单'
                    AND t1.F_RXWU_Text16<>'换货订单')
					SELECT * from #D where FSEQ=1
					union all
					select row_number() over(partition by t1.FENTRYID order by t1.FENTRYID  ) as FSEQ,T1.FENTRYID htFENTRYID,0 FEntryID,T.fbillno from T_CRM_CONTRACT t
					left join T_CRM_CONTRACTENTRY t1 on t.FID=t1.FID
					left join T_CRM_CONTRACTENTRY_R t2 on t1.FENTRYID=t2.FENTRYID
					LEFT join T_BD_MATERIAL t3 on t1.FMATERIALID=t3.FMATERIALID
					where t1.F_RXWU_QTY=0 and t2.FSALEQTY=0 
					AND T.F_RXWU_TEXT  IN (SELECT F_RXWU_Text6 FROM #F where FMATERIALID=T1.FMATERIALID)
                    union all
					SELECT row_number() over(partition by t3.FENTRYID order by t3.FENTRYID  ) as FSEQ, t3.FENTRYID htFENTRYID,T1.FEntryID,t3.FBILLNO from RXWU_t_Cust100002 t
					left join
					RXWU_t_Cust_Entry100013 t1 on  t.fid=t1.fid
					LEFT JOIN T_BD_MATERIAL T2 ON T1.FMATERIALID=T2.FMATERIALID
					right JOIN #C T3 ON T1.F_RXWU_Text6=T3.F_RXWU_TEXT AND T2.FNUMBER=T3.FNUMBER
					WHERE T1.F_RXWU_Text2='销售出仓'AND (t1.F_RXWU_Text16<>'补发订单'
                    AND t1.F_RXWU_Text16<>'换货订单')
					and (T1.F_RXWU_TEXT15='AutoCheck'OR T1.F_RXWU_TEXT15='UserCheck')
                    and (T1.F_RXWU_DATE2>t3.FDATE)
                    AND  t3.FDATE>(select max(fclosedate)fclosedate from t_stk_closeprofile where fcategory = 'STK' and FORGID=100071 group by forgid)
                    union all
					SELECT row_number() over(partition by t3.FENTRYID order by t3.FENTRYID  ) as FSEQ, t3.FENTRYID htFENTRYID,T1.FEntryID,t3.FBILLNO from RXWU_t_Cust100002 t
					left join
					RXWU_t_Cust_Entry100013 t1 on  t.fid=t1.fid
					LEFT JOIN T_BD_MATERIAL T2 ON T1.FMATERIALID=T2.FMATERIALID
					right JOIN #C T3 ON T1.F_RXWU_Text6=T3.F_RXWU_TEXT AND T2.FNUMBER=T3.FNUMBER
					WHERE T1.F_RXWU_Text2='销售出仓'
					and (T1.F_RXWU_TEXT15='UserAdjustment') and  t1.F_RXWU_Text16<>'换货订单'  and  t1.F_RXWU_Text16<>'补发订单'
                    AND  t3.FDATE>(select max(fclosedate)fclosedate from t_stk_closeprofile where fcategory = 'STK' and FORGID=100071 group by forgid)");
                    DynamicObjectCollection DynamData = DBUtils.ExecuteDynamicObject(ctx, SQL);
                    if (DynamData.Count > 0)
                    {
                        for (int i = 0; i < DynamData.Count; i++)
                        {
                            FEntryId = Convert.ToString(DynamData[i]["FEntryId"]);
                            htFENTRYID = Convert.ToString(DynamData[i]["htFENTRYID"]);
                            FBILLNO = Convert.ToString(DynamData[i]["FBILLNO"]);
                            string json = "{\"Ids\":\"\",\"Numbers\":[],\"EntryIds\":\""+ htFENTRYID + "\",\"RuleId\":\"028dd4bf-3098-4167-bad4-3b5ede77ed1f\",\"TargetBillTypeId\":\"\",\"TargetOrgId\":0,\"TargetFormId\":\"STK_TransferDirect\",\"IsEnableDefaultRule\":\"false\",\"IsDraftWhenSaveFail\":\"false\",\"CustomParams\":{}}";
                            result = InvokeHelper.Push("CRM_Contract", json.ToString());
                            JObject jobject = JObject.Parse(result);
                            string a = Convert.ToString(jobject["Result"]["ResponseStatus"]["IsSuccess"]);
                            bool IsSuccess = a == "True";
                            if (IsSuccess)
                            {
                                string SQL10 = "/*dialect*/" + string.Format(@"update T_CRM_CONTRACT set F_RXWU_Remarks='{1}',F_RXWU_CheckBox='1' where FBILLNO='{0}'", FBILLNO, result.ToString());
                                DBUtils.Execute(ctx, SQL10);
                                string SQL1 = "/*dialect*/" + string.Format(@"update RXWU_t_Cust_Entry100013 set F_RXWU_COMBO='1' where FEntryId='{0}'", FEntryId);
                                DBUtils.Execute(ctx, SQL1);
                                //Log.WriteLog("合同（退货单）自动下推销售直接调拨单成功", "报文:" + json.ToString() + "/r/n" + "返回结果:" + result.ToString() + "ctx:" + ctx);
                                var SuccessEntitysId = jobject["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Id"];
                                string SQL2 = "/*dialect*/" + string.Format(@"update T_CRM_CONTRACT set FXYDJID='{1}' where FBILLNO='{0}'", FBILLNO, SuccessEntitysId);
                                DBUtils.Execute(ctx, SQL2);
                                string Submit = "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\"" + SuccessEntitysId + "\",\"SelectedPostId\":0,\"NetworkCtrl\":\"\",\"IgnoreInterationFlag\":\"\"}";
                                result = InvokeHelper.Submit("STK_TransferDirect", Submit);
                                string Audit = "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\"" + SuccessEntitysId + "\",\"InterationFlags\":\"\",\"NetworkCtrl\":\"\",\"IsVerifyProcInst\":\"\",\"IgnoreInterationFlag\":\"\"}";
                                result = InvokeHelper.Audit("STK_TransferDirect", Audit);
                            }
                            else
                            {
                                string SQL10 = "/*dialect*/" + string.Format(@"update T_CRM_CONTRACT set F_RXWU_Remarks='{1}',F_RXWU_CheckBox='0' where FBILLNO='{0}'", FBILLNO, result.ToString());
                                DBUtils.Execute(ctx, SQL10);
                                //Log.WriteLog("合同（退货单）自动下推销售直接调拨单失败", "报文:" + json.ToString() + "/r/n" + "返回结果:" + result.ToString() + "ctx:" + ctx);
                                string SQL1 = "/*dialect*/" + string.Format(@"update RXWU_t_Cust_Entry100013 set F_RXWU_COMBO='0' where FEntryId='{0}'", FEntryId);
                                DBUtils.Execute(ctx, SQL1);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog("合同（退货单）自动下推销售直接调拨单程序报错", "原因:" + ex.ToString() + "ctx:" + ctx);
            }
        }
    }
}
